<template>
  <div>
    <el-dialog :visible.sync="visible"
               :title="title"
               width="95%"
               :before-close="modalClose"
               center
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-form :model="addForm"
               ref="addFormRef"
               :rules="addRules"
               label-width="100px">
        <el-form-item label="客户名称:"
                      prop="testStripId">
          <el-select v-model="addForm.organizationId"
                     placeholder="请选择客户名称"
                     @change="handleOrganization"
                     clearable
                     filterable
                     style="width:300px"
                     :disabled="isDisabled">
            <el-option :label="item.organizationName"
                       v-for="(item, index) in organizationList"
                       :key="index"
                       :value="item.organizationId +'_'+ item.type"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>

          <el-button type="primary"
                     @click="handleAdd"
                     :disabled="isDisabled">新 增</el-button>
        </el-form-item>
        <el-form-item label="发货管理:">
          <el-table border
                    :data="tableData">
            <el-table-column label="试纸名称"
                             prop="testStripId"
                             align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.testStripId"
                           placeholder="请选试纸名称"
                           clearable
                           class="w-200"
                           filterable
                           :disabled="isDisabled"
                           @change="changeTestStrip">
                  <el-option :label="item.testStripName"
                             v-for="item in testStripList"
                             :key="item.testStripId"
                             :value="item.testStripId"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="试纸厂家"
                             align="center"
                             prop="factoryId">
              <template slot-scope="scope">
                <el-select v-model="scope.row.factoryId"
                           placeholder="请选择试纸厂家"
                           clearable
                           class="w-200"
                           :disabled="isDisabled"
                           @change="changeFactory">
                  <el-option :label="item.factoryName"
                             v-for="item in factoryList"
                             :key="item.factoryId"
                             :value="item.factoryId"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="批号"
                             align="center"
                             prop="num">
              <template slot-scope="scope">
                <el-select v-model="scope.row.batchId"
                           placeholder="请选择批号"
                           class="w-200"
                           clearable
                           @change="changeBatch"
                           :disabled="isDisabled">
                  <el-option :label="item.batchNumber"
                             v-for="item in batchList"
                             :key="item.batchId"
                             :value="item.batchId"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="规格"
                             align="center"
                             prop="num">
              <template slot-scope="scope">
                <el-select v-model="scope.row.standardNum"
                           placeholder="请选择规格"
                           class="w-200"
                           clearable
                           @change="changeStandardUnit"
                           :disabled="isDisabled">
                  <el-option :label="`${item.standardNum}【${item.standardUnit}】`"
                             v-for="item in standardUnitList"
                             :key="item.standardNum"
                             :value="item.standardNum"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="包装"
                             align="center"
                             prop="num">
              <template slot-scope="scope">

                <el-select v-model="scope.row.packageNum"
                           placeholder="请选择包装单位"
                           class="w-200"
                           clearable
                           @change="changePackageUnit"
                           :disabled="isDisabled">
                  <el-option :label="`${item.packageNum}【${item.packageUnit}】`"
                             v-for="item in packageUnitList"
                             :key="item.packageNum"
                             :value="item.packageNum"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="数量"
                             align="center"
                             prop="num"
                             width="330">
              <template slot-scope="scope">
                <el-select v-model="scope.row.numUnit"
                           clearable
                           placeholder="请选择单位"
                           class="w-150"
                           @change="changeNumUnit"
                           :disabled="isDisabled">
                  <el-option :label="item.numUnit"
                             v-for="item in numUnitList"
                             :key="item.numUnit"
                             :value="item.numUnit"></el-option>
                </el-select>
                <el-input v-model="scope.row.deliveredNum"
                          :placeholder="`最大发货数量${num}`"
                          class="w-150"
                          :max="num"
                          :disabled="isDisabled"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作"
                             width="160"
                             align="center">
              <template slot-scope="scope">
                <el-button type="primary"
                           @click="saveForm(saveType, scope.$index, op)"
                           :disabled="isDisabled">保 存</el-button>
                <el-button type="danger"
                           @click="handleDelete(scope.$index, scope.row)"
                           :disabled="isDisabled">删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <p align="center">
          <el-button @click="modalClose"
                     v-if="isDetail">取 消</el-button>
          <el-button type="primary"
                     v-else
                     @click="modalClose">返 回</el-button>
          <!-- <el-button type="primary"
                     v-if="!isDetail"
                     @click="submitForm(addForm, isSubmitType)">保 存</el-button> -->
        </p>
      </el-form>

    </el-dialog>
  </div>
</template>
<script>
  export default {
    name: 'shipDialog',
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      isDetail: {
        type: Boolean,
        default: false
      },
      shipObj: {
        type: Object,
        default: {}
      }
    },
    data () {
      return {
        title: '',
        addForm: {
          organizationId: '', // 机构ID
          id: '', // 发货ID
          type: 1, // 机构类型（1：B端 2：医院）
          organizationName: '', // 机构名称
        },
        strOrganizationId: null,
        addRules: {},
        isShowCodeMod: false,
        isDisabled: false,
        tableData: [],
        organizationList: [], // 客户名称
        testStripList: [],
        factoryList: [],
        selectParams: {},
        batchList: [],
        standardUnitList: [],
        packageUnitList: [],
        numUnitList: [],
        currOrganization: {},
        currSandardUnit: {},
        currPackageUnit: {},
        currNumUnit: {},
        deliveredNum: '',
        num: '',
        saveType: '', // 保存的类型
        testStripDeliverDetailDto: {},
        op: '',
      }

    },
    methods: {
      // 关闭弹出框
      modalClose () {
        this.$emit('update:visible', false); // 直接修改父组件的属性 
        this.$parent.getList()
      },
      // 动态添加
      handleAdd () {
        this.op = 'addOption'
        let res = this.tableData
        if (res.length > 0) {
          let item = res[res.length - 1]
          if (item.testStripId === '') {
            this.$message.error('请选择试纸名称');
            return
          }
          this.tableData.push({
            testStripId: '',
            factoryId: '',
            batchId: '',
            standardUnit: '', // 规格单位
            standardNum: '', // 规格数量
            packageUnit: '', // 包装单位
            packageNum: '', // 包装数量
            numUnit: '', // 数量单位
            deliveredNum: '', // 发货数量
          })
        } else {
          this.tableData.push({
            testStripId: '',
            factoryId: '',
            batchId: '',
            standardUnit: '', // 规格单位
            standardNum: '', // 规格数量
            packageUnit: '', // 包装单位
            packageNum: '', // 包装数量
            numUnit: '', // 数量单位
            deliveredNum: '', // 发货数量
          })
        }

      },
      // 动态删除
      async handleDelete (index, row) {
        if (row.id) {
          this.$confirm('确认删除？')
            .then(async _ => {
              const { data: res } = await this.post(this.api.testStrip.delTestStripDeliverDetail, {
                id: this.shipObj.id,
                testStripDeliverDetailDto: {
                  id: row.id
                }
              })
              if (res.code === '200') {
                this.$message.success('删除成功')
                this.getTestStripDeliverDetail()
              }
            })
            .catch(_ => { });
        } else {
          this.tableData.splice(index, 1);
        }


      },
      async getCooperationOrganization () {
        const { data: res } = await this.post(this.api.testStrip.getCooperationOrganization, {
          organizationName: '',
          pageIndex: 0,
          pageSize: 100
        })
        if (res.code === '200') {
          this.organizationList = res.object.map(item => ({
            ...item,
            organizationName: item.organizationName + (item.type === 1 ? '【B端】' : '【合作机构】')
          }))
        }
      },
      // 选择客户名称
      handleOrganization (item) {
        this.strOrganizationId = Number(item.split('_')[0]);
        this.addForm.type = Number(item.split('_')[1]);
        let obj = this.organizationList.find(v => v.organizationId === Number(item.split('_')[0]));
        this.addForm.organizationName = obj.organizationName;
      },
      // 查询订单可发货的试纸
      async getOrderTestStripName () {
        const { data: res } = await this.post(this.api.testStrip.getOrderTestStripName, {
          testStripName: '',
          pageIndex: 0,
          pageSize: 100
        })
        if (res.code === '200') {
          this.testStripList = res.object
        }
      },
      // 选择试纸名称查询试纸厂商
      async changeTestStrip (item) {
        this.selectParams.testStripId = item
        await this.getOrderFactoryName()
      },
      // 查询订单可发货的试纸厂家
      async getOrderFactoryName () {
        const { data: res } = await this.post(this.api.testStrip.getOrderFactoryName, {
          // testStripId: this.selectParams.testStripId,
          factoryName: '',
          pageIndex: 0,
          pageSize: 100,
          ...this.selectParams
        })
        if (res.code === '200') {
          this.factoryList = res.object
        }
      },
      // 选择试纸厂家
      async changeFactory (item) {
        this.selectParams.factoryId = item
        await this.getOrderBatch()
      },

      // 查询订单可发货的厂家试纸批次
      async getOrderBatch () {
        const { data: res } = await this.post(this.api.testStrip.getOrderBatch, {
          // testStripId: this.selectParams.testStripId,
          // factoryId: this.selectParams.factoryId,
          batchNumber: '',
          pageIndex: 0,
          pageSize: 100,
          ...this.selectParams
        })
        if (res.code === '200') {
          this.batchList = res.object
        }
      },
      // 选择批号
      async changeBatch (item) {
        this.selectParams.batchId = item
        await this.getOrderStandard()
      },
      // 查询订单可发货的试纸规格
      async getOrderStandard () {
        const { data: res } = await this.post(this.api.testStrip.getOrderStandard, {
          // testStripId: this.selectParams.testStripId,
          // factoryId: this.selectParams.factoryId,
          // batchId: this.selectParams.batchId,
          ...this.selectParams
        })
        if (res.code === '200') {
          this.standardUnitList = res.object
        }
      },
      // 选择规格
      async changeStandardUnit (item) {
        this.currSandardUnit = this.standardUnitList.find(v => v.standardNum === item)
        await this.getOrderPackage()
      },
      // 查询订单可发货的试纸包装
      async getOrderPackage () {
        const { data: res } = await this.post(this.api.testStrip.getOrderPackage, {
          ...this.selectParams,
          ...this.currSandardUnit
        })
        if (res.code === '200') {
          this.packageUnitList = res.object
        }
      },
      // 选择包装
      async changePackageUnit (item) {
        this.currPackageUnit = this.packageUnitList.find(v => v.packageNum === item)
        await this.getOrderNumUnit()
      },
      // 查询订单可发货的试纸数量单位
      async getOrderNumUnit () {
        const { data: res } = await this.post(this.api.testStrip.getOrderNumUnit, {
          ...this.selectParams,
          ...this.currSandardUnit,
          ...this.currPackageUnit
        })
        if (res.code === '200') {
          this.numUnitList = res.object
        }
      },
      // 选择数量单位
      async changeNumUnit (item) {
        this.currNumUnit = this.numUnitList.find(v => v.numUnit === item)
        await this.getOrderNum()
      },
      // 查询订单可发货的试纸数量单位
      async getOrderNum () {
        const { data: res } = await this.post(this.api.testStrip.getOrderNum, {
          ...this.selectParams,
          ...this.currSandardUnit,
          ...this.currPackageUnit,
          ...this.currNumUnit,
        })
        if (res.code === '200') {
          this.num = res.object.num
          this.deliveredNum = res.object.deliveredNum
        }
      },
      // 保存
      async saveForm (saveType, index, op) {
        this.testStripDeliverDetailDto = {
          ...this.selectParams,
          ...this.currSandardUnit,
          ...this.currPackageUnit,
          ...this.currNumUnit,
        }
        if (saveType === 'add') { // 新增
          let { id, ...newForm } = this.testStripDeliverDetailDto
          const { data: res } = await this.post(this.api.testStrip.updateTestStripDeliver, {
            testStripDeliverDetailDto: {
              deliveredNum: Number(this.tableData[index].deliveredNum),
              ...newForm,
            },
            ...this.addForm,
            organizationId: this.strOrganizationId
          })

          if (res.code === '200') {
            this.$message.success('新增成功!')
            this.modalClose()
            this.$parent.getList()
          } else {
            this.$message.error(res.message)
          }
        }
        if (saveType === 'edit') {
          let { organizationId, ...params } = this.addForm;
          if (op === 'addOption') {
            let { id, ...newForm } = this.testStripDeliverDetailDto
            const { data: res } = await this.post(this.api.testStrip.updateTestStripDeliver, {
              testStripDeliverDetailDto: {
                deliveredNum: Number(this.tableData[index].deliveredNum),
                ...newForm,
              },
              ...params,
              organizationId: this.strOrganizationId
            })
            if (res.code === '200') {
              this.$message.success('新增成功!')
              this.modalClose()
              this.$parent.getList()
            } else {
              this.$message.error(res.message)
            }
          } else {
            const { data: res } = await this.post(this.api.testStrip.updateTestStripDeliver, {
              testStripDeliverDetailDto: this.tableData[index],
              ...params,
              organizationId: this.strOrganizationId
            })
            if (res.code === '200') {
              this.$message.success('修改成功!')
              this.modalClose()
              this.$parent.getList()
            } else {
              this.$message.error(res.message)
            }
          }
        }

      },
      // 获取试纸发货详情
      async getTestStripDeliverDetail () {
        const { data: res } = await this.post(this.api.testStrip.getTestStripDeliverDetail, {
          id: this.shipObj.id
        })
        let resData = res.object
        this.addForm.organizationId = resData.organizationId + '_' + resData.type
        this.strOrganizationId = resData.organizationId
        this.addForm.organizationName = resData.organizationName
        this.addForm.id = resData.id
        this.tableData = resData.testStripDeliverDetailDtos

        this.tableData.forEach(item => {
          // 通过试纸名称回显试纸厂家
          setTimeout(() => {
            this.changeTestStrip(item.testStripId)
          }, 0)
          // 通过试纸厂家回显批号
          setTimeout(() => {
            this.changeFactory(item.factoryId)
          }, 0)
          // 通过批号回显规格
          setTimeout(() => {
            this.changeBatch(item.batchId)
          }, 0)
          // 通过规格回显包装
          setTimeout(() => {
            this.changeStandardUnit(item.standardNum)
          }, 1000)
          // 通过包装回显数量
          setTimeout(() => {
            this.changePackageUnit(item.packageNum)
          }, 1500)
          // 通过包装回显数量单位
          setTimeout(() => {
            this.changeNumUnit(item.numUnit)
          }, 2000)

        })
      },
    },

    created () {
      this.getCooperationOrganization()
      this.getOrderTestStripName()
      if (this.shipObj) {
        this.getTestStripDeliverDetail() // 获取试纸发货详情
        this.saveType = 'edit'
        if (this.isDetail) {
          this.isDisabled = true
          this.title = '详 情'
        } else {
          // this.getOrderFactoryName()
          // this.getOrderBatch()
          // this.getOrderStandard()
          // this.getOrderNumUnit()
          // this.getOrderNum()
          this.title = '编 辑'
          this.isDisabled = false
        }
      } else {
        this.title = '新 增'
        this.saveType = 'add'
      }
    }
  }
</script>
<style lang="scss" scoped>
  .w-100 {
    width: 100px;
  }
  .w-150 {
    width: 150px;
  }
</style>